//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by niqiang on 16/7/7.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit
import SVProgressHUD

//通过webView 加载微博授权页面控制器
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white()
        
        //取消滚动视图 - 新浪微博的服务器，返回的授权码就是全屏
        webView.scrollView.isScrollEnabled = false
        
        //设置代理
        webView.delegate = self
        
        //设置导航栏
        title = "登录微博"
        
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autiFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        //1.URL确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        
        //2.建立请求
        let request = URLRequest(url: url)
        
        //3.加载请求
        webView.loadRequest(request)
    }
    
    // MARK: - 监听方法
    @objc private func close() {
    
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    
    }
    
    //自动填充 -WebView的注入 直接通过js修改“本地浏览器中”缓存的页面内容
    @objc private func autiFill() {
    
        //准备js
        let js = "document.getElementById('userId').value = '15311471503'; " +
        "document.getElementById('passwd').value = 'nq31381234';"

        //让webview 执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController: UIWebViewDelegate{

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.如果请求地址包含http://baidu.com不加载页面 / 否者加载页面
//        print("加载请求 \(request.url?.absoluteString)")
        
        if request.url?.absoluteString?.hasPrefix(WBRedirectURL)  == false {
            return true
        }
        //2.从http://itheima.com回调地址的“查询字符串”中查找“code=”
        //如果有，授权成功。否者，授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            
            return false
        }
        
        //3.从query 字符串中获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""

        //print("授权码 \(code)")
        //4.使用授权码获取【换取】AccessToken
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
            SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
//            SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //1.发送通知
                NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),object: nil)
                //2.关闭窗口
                self.close()
            }
        
        
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
